<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<link rel="stylesheet" type="text/css" href="./css/api.css" />
		<link rel="stylesheet" type="text/css" href="./css/style.css" />
		<style>
			html,body { height:100%; }
			.display-none { display:none; }
			.header .btn1{ position:absolute; top: 0; height: 100%; background-position: 22px; background-repeat: no-repeat; background-size: 22px auto;padding-left:10px;}
			.header .h_search1{ right: 15px; width: 35px; background-image: url(./image/img_67.png);}
		</style>
	</head>
	<body>
		<header class="header" id="home-header">
			<ul class="wrapper">
				<h1>首页</h1>
			</ul>
		</header>
		<header class="header" id="goods-header">
			<ul class="wrapper">
				<h1>配货大厅</h1>
				<a href="javascript:;" tapmode onclick="selRing();" class="btn1 h_search1"></a>
			</ul>
		</header>
		<header class="header" id="msg-header">
			<div class="h_tab" id="tablist">
				<a href="javascript:;" tapmode onclick="changetab(0);" class="on">消息</a>
				<a href="javascript:;" tapmode onclick="changetab(1);">好友</a>
			</div>
		</header>
		<header class="header" id="my-header">
			<ul class="wrapper">
				<h1>我的</h1>
			</ul>
		</header>
	</body>
	<script src="script/api.js"></script>
	<script src="script/app.js"></script>
	<script type="text/javascript" src="script/permission.js"></script>
	<script type="text/javascript">
		var NVTabBar;
		// 首页frame组
		var indexFrames = [];
		var msgFrames = ["msg_frm"];
		var currentFrameName = "home";
		var currentmsgFrameName = "msg_frm";
		var headIds = new Array("home","goods","msg","my");
		var avatar = '../image/defaultimg.png';
		var nickname = '注册/登录';
		var header_h = 50; //头部高度
		var bodyrect_h = 500; //默认body高度
		var ajpush,rong,headerH,footerH;
		var callId,dfuid;
		var myuid;
		apiready = function() {
			rong = api.require('rongCloud2');
			ajpush = api.require('ajpush');
			NVTabBar = api.require('NVTabBar');
			setTimeout(function() {
				api.removeLaunchView({
					animation : {
						type : 'fade',
						duration : 500
					}
				});
			}, 3000);
			// 判断是否已登录
			api.getPrefs({
				key: 'user_info'
			}, function(ret, err) {
				if (!ret.value) {
					setTimeout(function(){
						openNavWin('#fff','login_win','html/login/login_frm.html','',true,false,false,[],{});
					}, 0);
				}
				else
				{
					var userinfo = JSON.parse(ret.value);
					if(userinfo.status == -10)
					{
						
						
						//未人脸识别成功
					}
					else if(userinfo.status == -1)
					{
						api.removePrefs({
							key: 'user_info'
						});
						var userjson = {};
						var usersetting = 'updateuser('+ JSON.stringify(userjson) +');';
						//退出IM
						setTimeout(function(){
							openNavWin('#fff','login_win','html/login/login_frm.html','',true,false,true,[],{});
						}, 0);
					}
					else
					{
						//初始化IM
						myuid = userinfo.mobile;
						initrongyun(userinfo.rongcloud_token,0);//如果已登录，初始化融云模块和极光的绑定别名
						var param = {
							alias : userinfo.uid
						};
						ajpush.bindAliasAndTags(param, function(ret) {
							console.log('别名设置成功'+userinfo.uid);
						});	
					}
				}
			});
			initmeiqia();//初始化美洽
			if (api.systemType == "android") {
				
				ajpush.init(function(ret) {
				if (ret && ret.status){
						console.log('success');
						//success
					}
				});
			}
			api.addEventListener({
				name : 'keyback'
			}, function(ret, err) {
				api.toast({
					msg : '再点一下退出应用',
					duration : 2000,
					location : 'bottom'
				});
				api.addEventListener({
					name : 'keyback'
				}, function(ret, err) {
					api.closeWidget({
						silent : true
					});
				});
				setTimeout(function() {
					exitApp();
				}, 2000)
			});
			if (api.systemType == "android") {
				api.addEventListener({
					name: 'appintent'
				}, function(ret, err) {
					if (ret && ret.appParam.ajpush) {
						var ajpush = ret.appParam.ajpush;
						var id = ajpush.id;
						var title = ajpush.title;
						var content = ajpush.content;
						var extra = ajpush.extra;
						//console.log(extra.newsid);
						if(extra.newsid!='')
						{
							openNavWin('#ddd','pushmsg_win','html/msg/pushmsg_frm.html','订单提醒',false,false,true,[],{});
						}
						else
						{
							//api.sendEvent({
								//name : 'refreshsysmsg'
							//});
							//刷新msg
						}
					}
				});
			}else{
				api.addEventListener({
					name: 'noticeclicked'
				}, function(ret, err) {
					if (ret && ret.value) {
						var ajpush = ret.value;
						var content = ajpush.content;
						if(ajpush.extra)
						{
							var extra = ajpush.extra;
							if(extra.newsid)
							{
								openNavWin('#ddd','pushmsg_win','html/msg/pushmsg_frm.html','订单提醒',false,false,true,[],{});
							}
							else
							{
								//api.sendEvent({
									//name : 'refreshsysmsg'
								//});
								//刷新msg
							}
						}
						
						//
					}
				});
			}
			api.addEventListener({name:'pause'}, function(ret,err) {
				ajpush.onPause();//监听应用进入后台，通知jpush暂停事件
			});
                          
			api.addEventListener({name:'resume'}, function(ret,err) {
				ajpush.onResume();//监听应用恢复到前台，通知jpush恢复事件
			});
			
			api.addEventListener({
				name : 'refreshindex'
			}, function(ret, err) {
				freshPage(ret.value.userjson);
				
			});
			
			
			if (api.systemType != "android") {
				ajpush.setListener(function(ret, err){
					if(ret){
						api.sendEvent({
							name : 'refreshsysmsg'
						});
						//alert(JSON.stringify(ret)+"???/");
						if(ret.hasOwnProperty("extra"))
						{
							if(!ret.extra.hasOwnProperty("_j_business"))
							{
								notify(api.appName,ret.content,ret);
							}
						}
						else
						{
							if(ret.hasOwnProperty("extras"))
							{
								var rets = [];
								rets.content = ret.content;
								rets.extra = ret.extras;
								notify(api.appName,ret.content,rets);
							}
						}
					}
				});
			}
			else
			{
				ajpush.setListener(function(ret, err){
					if(ret){
						api.sendEvent({
							name : 'refreshsysmsg'
						});
					}
				});
			}
			var head = $api.byId('home-header');
			$api.fixStatusBar(head);
			var body = $api.dom('body');
			var head_h = $api.offset(head).h;;
			var body_h = $api.offset(body).h;
			
			var rect_h = body_h - head_h - 49 - api.safeArea.bottom;
			header_h = head_h; //设置头部高度
			bodyrect_h = rect_h; //设置frame rect区域高度
			headerH = header_h;
			footerH = rect_h;
			var ii = 0;
			api.openFrameGroup({
				scrollEnabled : false,
				name : 'anniu',
				rect : {
					x : 0,
					y : head_h,
					w : 'auto',
					h : rect_h
				},
				index : ii,
				preload: 3,
				frames : [{
					name : 'home_frm',
					url : 'html/home/home_frm.html',
					vScrollBarEnabled : false,
					hScrollBarEnabled : false,
				}, {
					name : 'lines_frm',
					url : 'html/lines/lines_frm.html',
					vScrollBarEnabled : false,
					hScrollBarEnabled : false,
				}, {
					name : 'msg_frm',
					url : 'html/msg/msg_frm.html',
					vScrollBarEnabled : false,
					hScrollBarEnabled : false,
					pageParam: {
						headH: head_h
					}
				}, {
					name : 'my_frm',
					url : 'html/my/my_frm.html',
					vScrollBarEnabled : false,
					hScrollBarEnabled : false,
				}]
			}, function(ret, err) {
			});
			showActiveFrame(0);
			footer();
			//setdepositfee();
		}
		function setdepositfee() {
			api.openFrame({
				name: 'depositfee_frm',
				url: 'html/goods/depositfee_frm.html',
				bounces: false,
				rect: {
					x: 0,
					y: 0,
					w: 'auto',
					h: 'auto'
				},
				bgColor: 'rgba(0,0,0,0.6)',
				pageParam: {
					
				}
			});	
		}
		function freshPage(userjson) {
			//刷新页面主逻辑
			myuid = userjson.mobile;
			//testinitrongyun(userjson.rongcloud_token);
			initrongyun(userjson.rongcloud_token,1);//如果已登录，初始化融云模块和极光的绑定别名
			var param = {
				alias : userjson.uid
			};
			ajpush.bindAliasAndTags(param, function(ret) {
				console.log('别名设置成功'+userjson.uid);
			});	
		}
		function reloadUnreadCount() {
			//重载未读数
			var iindex = 2;
			rong.getTotalUnreadCount(function(ret, err) {
				if(ret)
				{
					if(ret.result > 0)
					{
						var noreadnum = ret.result;
						if(noreadnum > 99)
						{
							noreadnum = '99+';
						}
						if(ret.result > 0)
						{
							NVTabBar.setBadge({
								index: iindex,
								badge: ''
							});
						}
					}
					else
					{
						NVTabBar.setBadge({
							index: iindex,
							//badge: '0'
						});
					}
				}
				
			});
		}
		function changeBadeg(badge) {
			var iindex = 2;
			if(badge > 0)
			{
				NVTabBar.setBadge({
					index: iindex,
					badge: ''
				});
			}
			else
			{
				NVTabBar.setBadge({
					index: iindex,
					//badge: '0'
				});
			}
		}
		function sendCall(jsondatastr) {
			//发起音视频聊天
			var jsondata = $api.strToJson(jsondatastr);
		}
		function initrongyun(token, reload){
			//初始化融云模块
			//reload为1则刷新我的客户列表
			var iindex = 2;
			rong.init(function(ret, err) {
				if (ret.status == 'success') {
					msglisten();//监听
					fnAddRongLisenter(); //监听音视频
					if (api.systemType == "android0") {
						rong.disconnect({
							isReceivePush: false
						}, function(ret, err) {
							if ('success' == ret.status) {
								fnRongConn(token,reload);
							}
						});
					}
					else
					{
						fnRongConn(token,reload);
					}
					
				}
				else if (ret.status == 'error') {
					api.toast({ msg: "登录失败，请退出重新登录！错误代码："+err.code });
				}
			});
			currentFrameName = "home";
			api.setFrameGroupIndex({
				name : 'anniu',
				index : 0
			});
			showActiveFrame(0);
			NVTabBar.setSelect({
				index: 0,
				selected: true
			});
		}
		function fnRongConn(token,reload) {
			//连接融云
			rong.connect({
				token : token
			}, function(ret, err) {
				if (ret.status == 'success') {
					//if(reload == 1)
					//{
						//通知我的客户页面刷新
						api.sendEvent({
							name : 'chatdialoglist'
						});
					//}
					reloadUnreadCount();//未读数
					
				}
				else if (ret.status == 'error') {
					if(err.code!='31006'){
						api.toast({ msg: err.code });
					}
				}
			});
		}
		function fnAddRongLisenter() {
			//添加融云监听事件
			rong.addCallReceiveListener({
				target: 'didReceiveCall'
			}, function(ret) {
				//toast('didReceiveCall:' + JSON.stringify(ret));
				var extramsg = $api.strToJson(ret.callSession.extra);
				callId = ret.callSession.callId;
				dfuid = ret.callSession.callerUserId;
				var dfnickname = extramsg.fromnickname;
				var dfavatar = extramsg.fromavatar;
				var mediaType = ret.callSession.mediaType;
				var param = {
					dfuid: dfuid,
					dfavatar: dfavatar,
					dfnickname: dfnickname,
					mediaType: mediaType,
					callId: callId,
					opentype: 'receive',
					showtime: 1
				};
				openNavWin('#fff','msgrongCloud_win','html/msg/msgrongCloud_frm.html','',true,false,false,[],param);
			});
			rong.addCallReceiveListener({
				target: 'permissionRequest'
			}, function(ret) {
				//请求开启权限
				var pername = new Array('phone','microphone','camera');
				var perdesc = '麦克风/摄像头';
				if (api.systemType == "android") {
					if(!confirmPerarr(pername,perdesc,'')){
						return;
					}
				}
			});
			rong.addCallSessionListener({
				target: 'didConnect'
			}, function(ret) {
				api.sendEvent({
					name : 'indexrecive'
				});
			});
			rong.addCallSessionListener({
				target: 'remoteUserDidJoin'
			}, function(ret) {
				console.log("对端用户加入了通话的事件:" + JSON.stringify(ret));
				dfuid = ret.userId;

				api.sendEvent({
					name : 'showvideo',
					extra : {
						uid : dfuid
					}
				});
				setTimeout(function(){
					api.sendEvent({
						name : 'showvideo',
						extra : {
							uid : myuid
						}
					});
					//1秒后显示本地视频，避免被遮挡
				}, 1000);
			});
			rong.addCallSessionListener({
				target: 'didDisconnect'
			}, function(ret) {
				console.log("通话已结束:" + JSON.stringify(ret));
				api.sendEvent({
					name : 'rongclouddisconn',
					extra : {
						reason : ret.disConnectReason
					}
				});
			});
		}
		function fnaccept(mediaType) {
			//alert(mediaType+'?'+callId);
			var params = {
				callId: callId
			}
			if (api.systemType == "ios") {
				params = {
					mediaType: mediaType
				}
				
			}
			rong.accept(params);
		}
		function fnhangup() {
			rong.hangup();
		}
		function fnsetVideoView(y, uid) {
			console.log(y+'?'+uid+api.systemType+api.winWidth+"!"+api.winHeight);
			var rect = {
				x: 0,
				y: 0,
				w: 'auto',
				h: 'auto'
			};
			if(uid == myuid) {
				rect = {
					x: 0,
					y: 0,
					w: 120,
					h: 180
				};
			}
			var fname = 'msgrongCloud_frm';
			rong.setVideoView({
				rect: rect,
				userId: uid,
				bg: '#ff0000',
				//renderModel: 'fit',
				//fixedOn: fname,
				fixed: true
			});
			
			//重新显示自己的区域
			
		}
		function msglisten(ver) {
			//var iindex = 2;
			rong.setOnReceiveMessageListener(function(ret, err) {
				if (ret) {
					api.sendEvent({
						name : 'chatdialoglist'
					});
					api.sendEvent({
						name : 'new_msg',
						extra : {
							msg : ret.result.message
						}
					});
					api.notification({
						vibrate:[300,500],
						sound:'default'
					});
					reloadUnreadCount();			
				}
			})
		}
		function initmeiqia() {
			//创建美洽
			var mq = api.require('meiQia');
			//配置初始化美洽需要的appkey
			var param = {
				appkey: "6d0e1a38a73fb97351a4a040074d89ac"
			};
			//初始化美洽
			mq.initMeiQia(param, function(ret, err) {
				if (ret) {
					//初始化成功
					//alert(JSON.stringify(ret));
				} else {
					//初始化失败
					//alert(JSON.stringify(err));
				}
			})
		}
		function changetab(index)
		{
			var liList = document.getElementById("tablist").children;
			for (var i = 0; i < liList.length; i++) {
				$api.removeCls(liList[i], 'on');
			}
			
			$api.addCls(liList[index],'on');
			
			showMsgFrame(index);
			
		}
		function openframe(framename, param) {
			api.openFrame({
				name: framename,
				url: 'html/msg/'+framename+'.html',
				bounces: false,
				rect: {
					x: 0,
					y: headerH,
					w: 'auto',
					h: api.winHeight - api.safeArea.top - 45 - 49 - api.safeArea.bottom
				},
				pageParam: param
			})
		}
		function showMsgFrame(index) {
			if(index == 0)
			{
				currentmsgFrameName = 'msg_frm';
			}
			else
			{
				currentmsgFrameName = 'friend_frm';
			}
			currentmsgFrameName = currentmsgFrameName.trim();
			if (msgFrames.indexOf(currentmsgFrameName) == -1) {
				openframe(currentmsgFrameName, {}); 
				msgFrames.push(currentmsgFrameName);
			}
			//tabFrame(currentmsgFrameName);//切换消息页面是否显示
			// 隐藏所有
			hideAllFrame(currentmsgFrameName);

		}
		function tabFrame(frameName) {
			var ishide = true;
			if(frameName == 'friend_frm')
			{
				ishide = false;
				//api.sendFrameToBack({
					//from: 'friend_frm'
				//});
				
			}
			//else
			//{
				//api.bringFrameToFront({
					//from: 'friend_frm'
				//});
			//}
			alert(ishide);
			api.setFrameAttr({
				name: 'friend_frm',
				hidden: ishide
			});
		}
		// 隐藏所有的frame
		function hideAllFrame(frameName) {
			for(var h in msgFrames){
				var curframe = msgFrames[h];
				console.log(curframe+'?');
				if (frameName != curframe) {
					
					api.setFrameAttr({
						name: curframe,
						hidden: true
					});
				} else {
					api.setFrameAttr({
						name: curframe,
						hidden: false
					});
				}
			}
		}
		function showActiveFrame(index) {
			var headerId = headIds[index];
			currentFrameName = headerId;
			var y_h = header_h;
			var h_h = bodyrect_h;
			if (api.systemType == "android") {
				api.setStatusBarStyle({
					style: 'dark',
					color : 'rgba(0,0,0,0.0)'
				});
			}
			else
			{
				api.setStatusBarStyle({
					style: 'dark'
				});
			}
			api.setFrameGroupAttr({
				name: 'anniu',
				rect: {
					x:0,             //左上角x坐标
					y:y_h,             //左上角y坐标
					w:'auto',           //宽度，若传'auto'，frame组从x位置开始自动充满父页面宽度
					h:h_h            //高度，若传'auto'，frame组从y位置开始自动充满父页面高度
				}
			});
			for(var h in headIds){
				$api.addCls($api.byId(headIds[h]+'-header'), 'display-none');
			}
			$api.removeCls($api.byId(headerId+'-header'), 'display-none');
			var head = $api.byId(currentFrameName+'-header');
			$api.fixStatusBar(head);

			var ishidemsg = currentFrameName == 'msg' ? false : true;
			api.setFrameAttr({
				name: currentmsgFrameName,
				hidden: ishidemsg
			});
		}
		function footer() {
			var x = 26,y = 7;
			if (api.systemType == "android") {
				x = 54;
				y = 4;
			}
			NVTabBar.open({
				styles: {
					bg: '#fff',
					h: 49,
					dividingLine: {
						width: 0.5,
						color: '#ddd'
					},
					badge: {
						bgColor: '#ff0000',
						numColor: '#fff',
						size: 8.0,
						centerX: x,
						centerY: y
					}
				},
				items: [{
					w: api.winWidth / 4.0,
					bg: {
						marginB: -1
					},
					iconRect: {
						w: 28.0,
						h: 28.0,
					},
					icon: {
						normal: 'widget://image/NVTabBar/home.png',
						highlight: 'widget://image/NVTabBar/home_on.png',
						selected: 'widget://image/NVTabBar/home_on.png'
					},
					title: {
						text: '首页',
						size: 10.0,
						normal: '#9F9F9F',
						selected: '#3262F1',
						marginB: 6.0
					}
				}, {
					w: api.winWidth / 4.0,
					bg: {
						marginB: -1
					},
					iconRect: {
						w: 28.0,
						h: 28.0,
					},
					icon: {
						normal: 'widget://image/NVTabBar/goods.png',
						highlight: 'widget://image/NVTabBar/goods_on.png',
						selected: 'widget://image/NVTabBar/goods_on.png'
					},
					title: {
						text: '配货大厅',
						size: 10.0,
						normal: '#9F9F9F',
						selected: '#3262F1',
						marginB: 6.0
					}
				}, {
					w: api.winWidth / 4.0,
					bg: {
						marginB: -1
					},
					iconRect: {
						w: 28.0,
						h: 28.0,
					},
					icon: {
						normal: 'widget://image/NVTabBar/msg.png',
						highlight: 'widget://image/NVTabBar/msg_on.png',
						selected: 'widget://image/NVTabBar/msg_on.png'
					},
					title: {
						text: '消息',
						size: 10.0,
						normal: '#9F9F9F',
						selected: '#3262F1',
						marginB: 6.0
					}
				}, {
					w: api.winWidth / 4.0,
					bg: {
						marginB: -1
					},
					iconRect: {
						w: 28.0,
						h: 28.0,
					},
					icon: {
						normal: 'widget://image/NVTabBar/my.png',
						highlight: 'widget://image/NVTabBar/my_on.png',
						selected: 'widget://image/NVTabBar/my_on.png'
					},
					title: {
						text: '我的',
						size: 10.0,
						normal: '#9F9F9F',
						selected: '#3262F1',
						marginB: 6.0
					}
				}],
				selectedIndex: 0
			}, function(ret, err) {
				if(typeof(ret.index)!="undefined"){
					var id = ret.index;
					api.setFrameGroupIndex({
						name : 'anniu',
						index : id
					});
					showActiveFrame(id);
				}
			});
		}
		function exitApp() {
			api.addEventListener({
				name : 'keyback'
			}, function(ret, err) {
				api.toast({
					msg : '再点一下退出应用',
					duration : 2000,
					location : 'bottom'
				});
				api.addEventListener({
					name : 'keyback'
				}, function(ret, err) {
					api.closeWidget({
						id : api.appId,
						retData : {
							name : 'closeWidget'
						},
						silent : true
					});
				});
				setTimeout(function() {
					exitApp();
				}, 3000)
			});
		}
		function notify(title,content,extra){
			api.notification({
				vibrate:[300, 500],
				sound:'default',
			    notify: {
			    	title: title, //标题，默认值为应用名称，只Android有效
			        content: content, //内容，默认值为'有新消息'
			        extra:extra, //传递给通知的数据，在通知被点击后，该数据将通过监听函数回调给网页
			        updateCurrent:false    //是否覆盖更新已有的通知，取值范围true|false。只Android有效
			    }
			}, function(ret, err){
			    if(ret){
			         //alert(JSON.stringify(ret));
			    }else{
			         //alert(JSON.stringify(err));
			    }
			});
		}
		function setselectid(selectname,con,type) {
			cameratype = con;
			$api.val($api.byId('cameratype'), selectname);
		}
		function selRing() {
			setTimeout(function(){
				api.openFrame({
					name: 'setring_frm',
					url: 'html/lines/setring_frm.html',
					bounces: false,
					rect: {
						x: 0,
						y: 0,
						w: 'auto',
						h: 'auto'
					},
					bgColor: 'rgba(0,0,0,0.6)',
					pageParam: {
					}
				});
			}, 0);
		}
	</script>
</html>